package com.wuzy.aidlserver;

import com.wuzy.aidlserver.slice.TransferAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.IAbilityConnection;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.bundle.ElementName;
import ohos.rpc.IRemoteObject;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.rpc.RemoteException;

import java.util.Arrays;

public class RemoteService extends Ability {
    private static final HiLogLabel TAG = new HiLogLabel(3, 0xD001100, "RemoteService");
    private boolean mIsBound;
    IMyIdlInterface iMyIdlInterface;

    @Override
    public void onStart(Intent intent) {
        HiLog.error(TAG, "RemoteService::onStart");
        super.onStart(intent);
        bindLocalService();
    }

    // 创建连接回调实例
    private IAbilityConnection connection = new IAbilityConnection() {
        // 连接到Service的回调
        @Override
        public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int resultCode) {
            // Client侧需要定义与Service侧相同的IRemoteObject实现类。开发者获取服务端传过来IRemoteObject对象，并从中解析出服务端传过来的信息。
            HiLog.error(TAG, "RemoteService::onAbilityConnectDone");
            mIsBound = true;
            iMyIdlInterface = MyIdlInterfaceStub.asInterface(iRemoteObject);
            try {
                iMyIdlInterface.bindSuccess();
            } catch (RemoteException e) {
                HiLog.error(TAG, "RemoteService::" + e.getMessage());
                HiLog.error(TAG, "RemoteService::" + Arrays.toString(e.getStackTrace()));
            }
        }

        // 断开与Service连接的回调
        @Override
        public void onAbilityDisconnectDone(ElementName elementName, int resultCode) {
            mIsBound = false;
            HiLog.error(TAG, "RemoteService::onAbilityDisconnectDone");
            createTransferAbility();
        }
    };

    private MyIdlInterfaceStub stub = new MyIdlInterfaceStub("com.wuzy.aidlserver.IMyIdlInterface") {
        @Override
        public void bindSuccess() throws RemoteException {
            HiLog.error(TAG, "RemoteService: bindSuccess");
        }

        @Override
        public void unbind() throws RemoteException {
            getApplicationContext().disconnectAbility(connection);
            HiLog.error(TAG, "RemoteService: disconnectAbility");
        }
    };

    private void createTransferAbility() {
        Intent secondIntent = new Intent();
        // 指定待启动FA的bundleName和abilityName
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.wuzy.aidlserver")
                .withAbilityName(TransferAbility.class)
                .build();
        secondIntent.setOperation(operation);
        secondIntent.setAction(TransferAbilitySlice.ACTION_FROM_SELF);
        secondIntent.setFlags(Intent.FLAG_ABILITY_NEW_MISSION);
        // 通过AbilitySlice的startAbility接口实现启动另一个页面
        startAbility(secondIntent);
        setTransitionAnimation(0,0);
    }

    /**
     * 绑定 LocalService
     */
    private void bindLocalService() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.wuzy.aidlclient")
                .withAbilityName("com.wuzy.aidlclient.LocalService")
                .build();
        intent.setOperation(operation);
        if (!getApplicationContext().connectAbility(intent, connection)) {
            HiLog.error(TAG, "RemoteService: 绑定 connectAbility 失败");
            terminateAbility();
        }
    }

    /**
     * 解除绑定 LocalService
     */
    private void unbindLocalService() {
        if (mIsBound) {
            try {
                iMyIdlInterface.unbind();
            } catch (RemoteException e) {
                HiLog.error(TAG, "RemoteService: " + e.getMessage());
                HiLog.error(TAG, "RemoteService: " + Arrays.toString(e.getStackTrace()));
            }
            getApplicationContext().disconnectAbility(connection);
            terminateAbility();
        }
    }

    @Override
    public void onBackground() {
        super.onBackground();
        HiLog.error(TAG, "RemoteService::onBackground");
    }

    @Override
    public void onStop() {
        super.onStop();
        HiLog.error(TAG, "RemoteService::onStop");
    }

    @Override
    public void onCommand(Intent intent, boolean restart, int startId) {
        HiLog.error(TAG, "RemoteService::onCommand");
    }

    @Override
    public IRemoteObject onConnect(Intent intent) {
        HiLog.error(TAG, "RemoteService::onConnect");
        return stub;
    }

    @Override
    public void onDisconnect(Intent intent) {
        super.onDisconnect(intent);
        HiLog.error(TAG, "RemoteService::onDisconnect");
    }
}